package com.ruoyi.user.service.impl;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.aliyun.AliPaymentConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.wx.TransferResponsEntity;
import com.ruoyi.common.wx.WxPaymentConfig;
import com.ruoyi.system.domain.UserSystemMsg;
import com.ruoyi.system.service.IUserSystemMsgService;
import com.ruoyi.user.domain.UserWithdrawRecord;
import com.ruoyi.user.mapper.UserCapitalFlowMapper;
import com.ruoyi.user.mapper.UserTotalCapitalMapper;
import com.ruoyi.user.mapper.UserWithdrawRecordMapper;
import com.ruoyi.user.service.IUserWithdrawRecordService;

/**
 * 提现明细Service业务层处理
 * 
 * @author DEREK
 * @date 2023-05-23
 */
@Service
public class UserWithdrawRecordServiceImpl extends ServiceImpl<UserWithdrawRecordMapper, UserWithdrawRecord> implements IUserWithdrawRecordService 
{
    @Autowired
    private UserWithdrawRecordMapper userWithdrawRecordMapper;
    @Autowired
    private WxPaymentConfig wxPaymentConfig;
    @Autowired
    private AliPaymentConfig aliPaymentConfig;
    @Autowired
    private UserCapitalFlowMapper userCapitalFlowMapper;
    @Autowired
	private UserTotalCapitalMapper userTotalCapitalMapper;
    @Autowired
    private IUserSystemMsgService userSystemMsgService;

    /**
     * 查询提现明细
     * 
     * @param id 提现明细主键
     * @return 提现明细
     */
    @Override
    public UserWithdrawRecord selectUserWithdrawRecordById(Long id)
    {
        return userWithdrawRecordMapper.selectUserWithdrawRecordById(id);
    }

    /**
     * 查询提现明细列表
     * 
     * @param userWithdrawRecord 提现明细
     * @return 提现明细
     */
    @Override
    public List<UserWithdrawRecord> selectUserWithdrawRecordList(UserWithdrawRecord userWithdrawRecord)
    {
        return userWithdrawRecordMapper.selectUserWithdrawRecordList(userWithdrawRecord);
    }

    /**
     * 新增提现明细
     * 
     * @param userWithdrawRecord 提现明细
     * @return 结果
     */
    @Override
    public int insertUserWithdrawRecord(UserWithdrawRecord userWithdrawRecord)
    {
        userWithdrawRecord.setCreateTime(DateUtils.getNowDate());
        return userWithdrawRecordMapper.insertUserWithdrawRecord(userWithdrawRecord);
    }

    /**
     * 修改提现明细
     * 
     * @param userWithdrawRecord 提现明细
     * @return 结果
     */
    @Override
    public int updateUserWithdrawRecord(UserWithdrawRecord userWithdrawRecord)
    {
        return userWithdrawRecordMapper.updateUserWithdrawRecord(userWithdrawRecord);
    }

    /**
     * 批量删除提现明细
     * 
     * @param ids 需要删除的提现明细主键
     * @return 结果
     */
    @Override
    public int deleteUserWithdrawRecordByIds(Long[] ids)
    {
        return userWithdrawRecordMapper.deleteUserWithdrawRecordByIds(ids);
    }

    /**
     * 删除提现明细信息
     * 
     * @param id 提现明细主键
     * @return 结果
     */
    @Override
    public int deleteUserWithdrawRecordById(Long id)
    {
        return userWithdrawRecordMapper.deleteUserWithdrawRecordById(id);
    }

	@Override
	@Transactional
	public AjaxResult withdrawalHandle(UserWithdrawRecord userWithdrawRecord,String nickName) {
		UserWithdrawRecord withdraw = userWithdrawRecordMapper.selectById(userWithdrawRecord.getId());
		String remark = "";
		if(null == withdraw) {
			return AjaxResult.error("提现记录不存在");
		}
		if(1 == withdraw.getStatus() && 0 == withdraw.getAbnormal()) {
			return AjaxResult.error("提现已处理");
		}
//		PriceSetting priceSet = priceSettingMapper.selectOne(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "提现比例")
//				.select(PriceSetting::getId,PriceSetting::getCurrentPrice));
//		BigDecimal scale = new BigDecimal("1");//提现比例
//		if(null != priceSet && null != priceSet.getCurrentPrice()) {
//			scale = priceSet.getCurrentPrice();
//		}
//		BigDecimal chargeAmount = new BigDecimal(withdraw.getWithdrawAmount().multiply(scale).setScale(2, BigDecimal.ROUND_DOWN).toPlainString());
		if(1 == userWithdrawRecord.getStatus()) { // 通过
			this.update(new UpdateWrapper<UserWithdrawRecord>().lambda().eq(UserWithdrawRecord::getId, withdraw.getId())
					.set(UserWithdrawRecord::getStatus, 1).set(UserWithdrawRecord::getReason, "通过").set(UserWithdrawRecord::getOperateExplain, nickName)
					.set(UserWithdrawRecord::getWithdrawTime, new Date()));
			// 修改流水
			userCapitalFlowMapper.withdrawalHandle(userWithdrawRecord.getStatus(), "通过", withdraw.getOrderNo(),withdraw.getWithdrawAmount());
			// 修改用户余额
			userTotalCapitalMapper.updUserAmount(withdraw.getWithdrawAmount(), withdraw.getUserId(), 1);
			if(1 == withdraw.getWithdrawTo()) {// 微信
				TransferResponsEntity entity = null;
				try {
					entity = wxPaymentConfig.payToUser(withdraw.getOrderNo(), withdraw.getBackAccount(), Double.valueOf(withdraw.getWithdrawAmount().toPlainString()));
				}  catch (Exception e) {
					e.printStackTrace();
					throw new GlobalException(e.getMessage());
				}
				if(null == entity || StringUtils.isEmpty(entity.getBatch_id())) {
					throw new GlobalException(entity.getMessage());
				}
				
			}else if(2 == withdraw.getWithdrawTo()) {// 支付宝
				JSONObject aliPayToUser;
				try {
					aliPayToUser = aliPaymentConfig.aliPayToUser(withdraw.getOrderNo(), withdraw.getBackAccount(), withdraw.getWithdrawAmount().toPlainString(), withdraw.getRealName());
				} catch (AlipayApiException e) {
					throw new GlobalException(e.getMessage());
				}
				if(0 == aliPayToUser.getInteger("status")) {
					throw new GlobalException(aliPayToUser.getString("msg"));
				}
			}else {
				return AjaxResult.error("未知提现方式");
			}
			remark = "您的提现申请已经审核通过,请留意手机收款消息！";
		}else { // 拒绝
			this.update(new UpdateWrapper<UserWithdrawRecord>().lambda().eq(UserWithdrawRecord::getId, withdraw.getId())
					.set(UserWithdrawRecord::getStatus, 2).set(UserWithdrawRecord::getReason, userWithdrawRecord.getReason()).set(UserWithdrawRecord::getOperateExplain, nickName)
					.set(UserWithdrawRecord::getWithdrawTime, new Date()));
			userCapitalFlowMapper.withdrawalHandle(2, userWithdrawRecord.getReason(), withdraw.getOrderNo(),withdraw.getWithdrawAmount());
			userTotalCapitalMapper.updUserAmount(withdraw.getWithdrawAmount(), withdraw.getUserId(), 2);
			remark = "您的提现申请被拒绝,理由："+userWithdrawRecord.getReason();
		}
		// 推送消息
		UserSystemMsg userSystemMsg = new UserSystemMsg();
		userSystemMsg.setUserId(withdraw.getUserId());
		userSystemMsg.setTitle("提现状态");
		userSystemMsg.setContent(remark);
		userSystemMsgService.save(userSystemMsg);
		return AjaxResult.success();
	}
}
